package com.movie.ui;

import com.movie.model.Movie;
import com.movie.model.Screening;
import com.movie.model.Ticket;
import com.movie.service.MovieService;
import com.movie.service.UserService;
import com.movie.service.DataService;
import com.movie.util.ApiDocUtil;
import javax.swing.*;
import java.awt.*;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class UserUI extends JFrame {
    private MovieService movieService;
    private UserService userService;
     private DataService dataService;
    private JList<Movie> movieList;
    private JTextArea screeningListArea;
    private JTextArea ticketListArea;
    private DefaultListModel<Movie> listModel;


    public UserUI(MovieService movieService, UserService userService, DataService dataService) {
        this.movieService = movieService;
        this.userService = userService;
         this.dataService = dataService;
        setTitle("用户系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout());

        listModel = new DefaultListModel<>();
        movieList = new JList<>(listModel);
        movieList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        movieList.addListSelectionListener(e -> showScreenings());
        JScrollPane movieListScrollPane = new JScrollPane(movieList);

        screeningListArea = new JTextArea();
        screeningListArea.setEditable(false);
        JScrollPane screeningScrollPane = new JScrollPane(screeningListArea);

        ticketListArea = new JTextArea();
        ticketListArea.setEditable(false);
        JScrollPane ticketScrollPane = new JScrollPane(ticketListArea);

        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JTextField searchField = new JTextField(20);
        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(e -> searchMovie(searchField.getText()));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        JPanel screeningControlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JTextField bookTicketField = new JTextField(10);
        JButton bookTicketButton = new JButton("Book Ticket");
        bookTicketButton.addActionListener(e -> bookTicket(bookTicketField.getText()));
        JButton viewTicketsButton = new JButton("My Tickets");
        viewTicketsButton.addActionListener(e -> viewTickets());
         JButton deleteTicketButton = new JButton("Delete Ticket");
        deleteTicketButton.addActionListener(e -> deleteTicket());

        JButton exitButton = new JButton("Exit");
        exitButton.addActionListener(e -> dispose());

         //创建 API 文档按钮
        JButton apiDocButton = new JButton("API 文档");
         apiDocButton.addActionListener(e -> {
            ApiDocUtil.showMovieApiDocument(this);
            ApiDocUtil.showUserApiDocument(this);
        });

        screeningControlPanel.add(bookTicketField);
        screeningControlPanel.add(bookTicketButton);
        screeningControlPanel.add(viewTicketsButton);
        screeningControlPanel.add(deleteTicketButton);
        screeningControlPanel.add(apiDocButton);
        screeningControlPanel.add(exitButton);


        JPanel splitPanel = new JPanel(new BorderLayout());
        splitPanel.add(screeningScrollPane, BorderLayout.CENTER);
        splitPanel.add(screeningControlPanel, BorderLayout.SOUTH);

        JSplitPane movieAndScreeningSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, movieListScrollPane, splitPanel);
        movieAndScreeningSplitPane.setResizeWeight(0.3);
        movieAndScreeningSplitPane.setDividerLocation(200);

        JSplitPane mainSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, movieAndScreeningSplitPane,ticketScrollPane );
        mainSplitPane.setResizeWeight(0.7);
        mainSplitPane.setDividerLocation(450);


        add(searchPanel, BorderLayout.NORTH);
        add(mainSplitPane, BorderLayout.CENTER);
       addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
           public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                System.exit(0);
           }
        });
        loadMovies();
        setVisible(true);
    }


    private void loadMovies() {
       listModel.clear();
        List<Movie> movies = movieService.searchMovies("");
        for (Movie movie : movies) {
            listModel.addElement(movie);
        }
    }

    private void searchMovie(String keyword){
        listModel.clear();
        List<Movie> movies = movieService.searchMovies(keyword);
        for (Movie movie : movies) {
           listModel.addElement(movie);
        }
    }

    private void showScreenings(){
        Movie selectedMovie = movieList.getSelectedValue();
        if(selectedMovie == null){
            return;
        }
        List<Screening> screenings = movieService.getScreeningsByMovie(selectedMovie.getId());
        if(screenings.isEmpty()){
           screeningListArea.setText("No screenings found for this movie");
            return;
        }
       StringBuilder sb = new StringBuilder();
       DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
      for (Screening screening : screenings) {
            sb.append("ID: ").append(screening.getId()).append("\n");
             sb.append("Start Time: ").append(screening.getStartTime().format(formatter)).append("\n");
            sb.append("Price: ").append(screening.getPrice()).append("\n");
           sb.append("Available Seats: ").append(screening.getSeatsAvailable()).append("\n");
           sb.append("---------------------\n");
         }
       screeningListArea.setText(sb.toString());
   }

    private void bookTicket(String screeningId) {
        if(screeningId.isEmpty()){
            JOptionPane.showMessageDialog(this,"Please input Screening ID");
            return;
        }
        Screening screening = movieService.getScreeningById(screeningId);
        if(screening == null){
           JOptionPane.showMessageDialog(this,"Invalid Screening Id");
           return;
        }
       if(screening.getSeatsAvailable() <= 0){
            JOptionPane.showMessageDialog(this,"No more seats available");
           return;
        }
        String seatInput = JOptionPane.showInputDialog(this,"Please input the seat number");
       try{
            int seatNumber = Integer.parseInt(seatInput);
           Ticket ticket =  userService.bookTicket(screeningId,seatNumber);
           if(ticket == null){
               JOptionPane.showMessageDialog(this,"Failed to book the ticket");
               showScreenings();
              return;
          }
            JOptionPane.showMessageDialog(this,"Ticket booked successfully. Ticket ID: " + ticket.getId() +", Seat Number: " + ticket.getSeatNumber());
             showScreenings();
        }catch (NumberFormatException exception){
            JOptionPane.showMessageDialog(this,"Invalid seat number");
        }

   }

    private void viewTickets(){
        List<Ticket> tickets = userService.getMyTickets();
        if(tickets.isEmpty()){
            ticketListArea.setText("No tickets booked");
            return;
        }
         StringBuilder sb = new StringBuilder();
        for (Ticket ticket : tickets) {
             sb.append("Ticket ID: ").append(ticket.getId()).append("\n");
             sb.append("Screening ID: ").append(ticket.getScreeningId()).append("\n");
             sb.append("Seat Number: ").append(ticket.getSeatNumber()).append("\n");
            sb.append("--------------------\n");
       }
        ticketListArea.setText(sb.toString());
    }

    private void deleteTicket(){
        String ticketId = JOptionPane.showInputDialog(this,"Please input Ticket ID you want to delete");
         if(ticketId == null || ticketId.isEmpty()){
             return;
         }
        userService.deleteTicket(ticketId);
        viewTickets();
    }
}